package com.example.security.config;

import com.example.security.filter.MyAuthenticationFilter;
import com.example.security.service.UserInfoService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @application:
 * @author: LiYuhang
 * @Date: 2021/3/21 18:13
 * @version: 0.1
 * @Description :
 * @Modified By:
 */
@Configuration
public class SecurityConfig  extends WebSecurityConfigurerAdapter {
    @Resource
    UserInfoService userInfoService;

    /**
     * 加密器
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userInfoService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
                .and().formLogin().permitAll()
                .and().logout().logoutUrl("/logout")
                .and().logout().logoutSuccessHandler(new LogoutSuccessHandler() {
            @Override
            public void onLogoutSuccess(HttpServletRequest req,HttpServletResponse res,Authentication authentication) throws IOException, ServletException {
                res.setContentType("application/json;charset=utf-8");
                PrintWriter out = res.getWriter();
                Map<String, Object> map = new HashMap<>();
                map.put("status", 200);
                map.put("msg", "注销登录成功!");
                out.write(new ObjectMapper().writeValueAsString(map));
                out.flush();
                out.close();
            }
        }).and().csrf().disable();
        http.addFilterAt(myAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    MyAuthenticationFilter myAuthenticationFilter() throws Exception {
        MyAuthenticationFilter filter = new MyAuthenticationFilter();
        filter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication authentication) throws IOException, ServletException {
                res.setContentType("application/json;charset=utf-8");
                PrintWriter out = res.getWriter();
                Map<String, Object> map = new HashMap<>();
                map.put("status", 200);
                map.put("msg", authentication.getPrincipal());
                out.write(new ObjectMapper().writeValueAsString(map));
                out.flush();
                out.close();
            }
        });
        filter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException e) throws IOException, ServletException {
                res.setContentType("application/json;charset=utf-8");
                PrintWriter out = res.getWriter();
                Map<String, Object> map = new HashMap<>();
                map.put("status", 401);
                if (e instanceof LockedException) {
                    map.put("msg", "账户被锁定，登录失败!");
                } else if (e instanceof UsernameNotFoundException) {
                    map.put("msg", "用户名不存在!");
                } else if (e instanceof BadCredentialsException) {
                    map.put("msg", "用密码输入错误，登录失败!");
                } else if (e instanceof DisabledException) {
                    map.put("msg", "账户被禁用，登录失败!");
                } else if (e instanceof AccountExpiredException) {
                    map.put("msg", "账户过期，登录失败!");
                } else if (e instanceof CredentialsExpiredException) {
                    map.put("msg", "密码过期，登录失败!");
                } else {
                    map.put("msg", "登录失败!");
                }
                out.write(new ObjectMapper().writeValueAsString(map));
                out.flush();
                out.close();
            }
        });
        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }
}
